package com.bigdata.schaduler.client;

import lombok.extern.slf4j.Slf4j;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
import org.jetbrains.annotations.NotNull;

import java.io.IOException;

@Slf4j
public class LoggingInterceptor implements Interceptor {
  @NotNull
  @Override
  public Response intercept(@NotNull Chain chain) throws IOException {
    Request request = chain.request();

    String requestLog = "请求海豚调度系统URL[%s], METHOD[%s], BODY[%s]";
    String requestContent = "";
    if (request.body() != null) {
      Buffer buffer = new Buffer();
      request.body().writeTo(buffer);
      requestContent = buffer.readUtf8();
    }
    log.info(String.format(requestLog, request.url(), request.method(), requestContent));

    Response response = chain.proceed(request);

    String responseLog = "海豚调度系统响应CODE[%s], MSG[%s], BODY[%s]";
    String responseContent = "";
    if (response.body() != null) {
      ResponseBody responseBody = response.peekBody(Long.MAX_VALUE);
      responseContent = responseBody.string();
    }
    log.info(String.format(responseLog, response.code(), response.message(), responseContent));

    return response;
  }
}